<template>
    <div class="order-list-container">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>订单列表</span>
          </div>
        </template>
        
        <!-- 搜索表单 -->
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="订单号">
            <el-input v-model="searchForm.orderId" placeholder="请输入订单号" clearable />
          </el-form-item>
          
          <el-form-item label="用户名/手机">
            <el-input v-model="searchForm.user" placeholder="请输入用户名/手机" clearable />
          </el-form-item>
          
          <el-form-item label="订单状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
              <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="下单时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
        
        <!-- 订单表格 -->
        <el-table
          :data="orderList"
          border
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="id" label="订单号" width="180" />
          
          <el-table-column prop="user" label="用户" width="120" />
          
          <el-table-column prop="phone" label="联系电话" width="140" />
          
          <el-table-column prop="amount" label="订单金额" width="120">
            <template #default="scope">
              ¥{{ (scope.row.amount || 0).toFixed(2) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="status" label="订单状态" width="120">
            <template #default="scope">
              <el-tag :type="getStatusType(getStatusText(scope.row.status))">{{ getStatusText(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="paymentMethod" label="支付方式" width="120">
            <template #default="scope">
              {{ getPaymentMethodText(scope.row.paymentMethod) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="createTime" label="下单时间" width="180" />
          
          <el-table-column fixed="right" label="操作" width="200">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="viewDetail(scope.row)">查看详情</el-button>
              
              <el-button
                v-if="scope.row.status === '待发货'"
                link
                type="success"
                size="small"
                @click="handleShip(scope.row)"
              >
                发货
              </el-button>
              
              <el-button
                v-if="scope.row.status === '待付款'"
                link
                type="danger"
                size="small"
                @click="handleCancel(scope.row)"
              >
                取消
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
      
      <!-- 发货弹窗 -->
      <el-dialog
        v-model="shipDialogVisible"
        title="订单发货"
        width="500px"
      >
        <el-form :model="shipForm" label-width="100px">
          <el-form-item label="物流公司">
            <el-select v-model="shipForm.company" placeholder="请选择物流公司" style="width: 100%">
              <el-option label="顺丰速运" value="SF" />
              <el-option label="中通快递" value="ZTO" />
              <el-option label="圆通速递" value="YTO" />
              <el-option label="韵达快递" value="YD" />
              <el-option label="申通快递" value="STO" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="快递单号">
            <el-input v-model="shipForm.trackingNumber" placeholder="请输入快递单号" />
          </el-form-item>
          
          <el-form-item label="发货备注">
            <el-input
              v-model="shipForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息（选填）"
            />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="shipDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmShip" :loading="submitting">确认发货</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { getOrderList, updateOrderStatus } from '../../api/order'
  
  const router = useRouter()
  const loading = ref(false)
  const submitting = ref(false)
  
  // 订单状态选项
  const statusOptions = [
    { label: '待付款', value: '待付款' },
    { label: '待发货', value: '待发货' },
    { label: '已发货', value: '已发货' },
    { label: '已完成', value: '已完成' },
    { label: '已取消', value: '已取消' },
    { label: '已退款', value: '已退款' }
  ]
  
  // 获取状态对应的标签类型
  const getStatusType = (status) => {
    const map = {
      '待付款': 'warning',
      '待发货': 'info',
      '已发货': 'primary',
      '已完成': 'success',
      '已取消': 'danger',
      '已退款': 'danger'
    }
    return map[status] || 'info'
  }
  
  // 搜索表单
  const searchForm = reactive({
    orderId: '',
    user: '',
    status: '',
    dateRange: []
  })
  
  // 分页信息
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })
  
  // 订单列表数据
  const orderList = ref([])
  
  // 获取订单列表
  const fetchOrderList = async () => {
    loading.value = true
    
    try {
      const params = {
        page: pagination.currentPage,
        limit: pagination.pageSize,
        orderId: searchForm.orderId,
        user: searchForm.user,
        status: searchForm.status,
        startDate: searchForm.dateRange?.[0],
        endDate: searchForm.dateRange?.[1]
      }
      
      const res = await getOrderList(params)
      
      // 处理返回数据，确保金额字段为数字类型
      orderList.value = res.items.map(item => ({
        ...item,
        amount: parseFloat(item.total_amount || item.amount || 0),
        createTime: item.created_at,
        paymentMethod: item.payment_method
      }))
      
      pagination.total = res.total
    } catch (error) {
      ElMessage.error('获取订单列表失败: ' + error.message)
    } finally {
      loading.value = false
    }
  }
  
  // 搜索
  const handleSearch = () => {
    pagination.currentPage = 1
    fetchOrderList()
  }
  
  // 重置搜索
  const resetSearch = () => {
    searchForm.orderId = ''
    searchForm.user = ''
    searchForm.status = ''
    searchForm.dateRange = []
    handleSearch()
  }
  
  // 查看订单详情
  const viewDetail = (row) => {
    router.push(`/orders/${row.id}`)
  }
  
  // 发货相关
  const shipDialogVisible = ref(false)
  const currentOrder = ref(null)
  const shipForm = reactive({
    company: '',
    trackingNumber: '',
    remark: ''
  })
  
  // 打开发货弹窗
  const handleShip = (row) => {
    currentOrder.value = row
    shipDialogVisible.value = true
    // 重置表单
    shipForm.company = ''
    shipForm.trackingNumber = ''
    shipForm.remark = ''
  }
  
  // 确认发货
  const confirmShip = async () => {
    if (!shipForm.company) {
      ElMessage.warning('请选择物流公司')
      return
    }
    
    if (!shipForm.trackingNumber) {
      ElMessage.warning('请输入快递单号')
      return
    }
    
    submitting.value = true
    
    try {
      await updateOrderStatus(currentOrder.value.id, {
        status: '已发货',
        logisticsCompany: shipForm.company,
        trackingNumber: shipForm.trackingNumber,
        shippingRemark: shipForm.remark
      })
      
      currentOrder.value.status = '已发货'
      ElMessage.success('发货成功')
      shipDialogVisible.value = false
      fetchOrderList()
    } catch (error) {
      ElMessage.error('发货失败: ' + error.message)
    } finally {
      submitting.value = false
    }
  }
  
  // 取消订单
  const handleCancel = (row) => {
    ElMessageBox.confirm(`确定要取消订单 ${row.id} 吗?`, '取消订单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        await updateOrderStatus(row.id, { status: '已取消' })
        ElMessage.success('订单已取消')
        fetchOrderList()
      } catch (error) {
        ElMessage.error('取消订单失败: ' + error.message)
      }
    }).catch(() => {})
  }
  
  // 分页大小变化
  const handleSizeChange = (size) => {
    pagination.pageSize = size
    fetchOrderList()
  }
  
  // 页码变化
  const handleCurrentChange = (page) => {
    pagination.currentPage = page
    fetchOrderList()
  }
  
  // 获取支付方式文本
  const getPaymentMethodText = (paymentMethod) => {
    const map = {
      'alipay': '支付宝',
      'wechat': '微信支付'
    }
    return map[paymentMethod] || paymentMethod
  }
  
  // 获取状态文本
  const getStatusText = (status) => {
    const map = {
      '待付款': '待付款',
      '待发货': '待发货',
      '已发货': '已发货',
      '已完成': '已完成',
      '已取消': '已取消',
      '已退款': '已退款',
      'pending': '待付款',
      'paid': '待发货',
      'shipped': '已发货',
      'completed': '已完成',
      'cancelled': '已取消',
      'refunded': '已退款'
    }
    return map[status] || status
  }
  
  onMounted(() => {
    fetchOrderList()
  })
  </script>
  
  <style scoped>
  .order-list-container {
    padding: 20px;
    background-color: #f0f2f5;
    min-height: calc(100vh - 60px);
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .box-card {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  </style>